package org.example.all;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

/**
 * @author Yyming
 * @version 10.0
 * Created by Yyming on 2020/11/4
 */
public class EffectiveCache1 {
    //用来存储缓存对象
    private static final Map<String, Object> cache = new ConcurrentHashMap<>();

    //获取需要的缓存对象,不存在就创建一个
    public Object getOne(String key) {
        Object o = cache.get(key);
        if (o == null) {
            o = this.produce(key);
            cache.put(key, o);
        }
        return o;
    }

    private Object produce(String key) {
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return new Object();
    }
}
